//
//  LIstController.m
//  diaoyuren
//
//  Created by Cheng on 16/2/5.
//  Copyright © 2016年 game. All rights reserved.
//

#import "LIstController.h"
#import "NewsCell.h"
#import "UIImageView+WebCache.h"
#import "CharacterCell.h"
#import "Recomment.h"
#import "NewestAticleCtr.h"
#import "Manager.h"
#import "ClassiFYModel.h"
#import "ClassListModel.h"
#import "PageInfoModel.h"
#import "ShoolDataModel.h"
#import "NewstModel.h"
#import "NEWAticListModel.h"
#import "NewRecomModel.h"
#import "CGFdbmBase.h"
#import "PramasMontage.h"
#import "VideoDescrib.h"
#import "SlideBntView.h"
#import "QuarterView.h"
#import "UIScrollView+EmptyDataSet.h"
#import "RootTableview.h"
#import "MJRefresh.h"
@interface LIstController ()<UITableViewDataSource,UITableViewDelegate,SlideBtnViewDeleget,QuarViewClickDeleget,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
{
    CGFloat _cellHeight;
    CGFloat _CharacCellHeight;
    UIImageView *_downimg;
    BOOL isClick;
    NSMutableArray *_CharaDataAry;
    ClassiFYModel  *_classfyModel;
    NSMutableArray *_dataAry;
    ShoolDataModel *_model;
    PageInfoModel *_infoModel;
    NewstModel *_newstModel;
    NEWAticListModel *_AticModel3;
    Recomment *_recommentView;
    NSMutableArray *_listAry;
    NSMutableArray *_recomAry;
    UILabel *_titleLabel;
    NSInteger _refreshNumb;
    NSInteger _bigCharectAid;
    NSInteger _smallCharactAid;
}
@property (nonatomic, copy) NSString * bqStr;
@property (nonatomic,strong) SlideBntView *slideBntview;
//@property (nonatomic , strong) QuartModel *model;
@property (nonatomic,strong) QuarterView *quarView;
@property (nonatomic,strong)NSString  *QuaRefrshUrl;
@property (nonatomic,strong)  RootTableview *tableview;
@property (nonatomic,strong)UITableView *ClassifyTableview;//分类tableview
@end

@implementation LIstController
-(void)creatquarView
{
    [self.quarView removeFromSuperview];
    self.quarView=[[QuarterView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, 60)];
    self.quarView.deleget=self;
    _tableview.frame = CGRectMake(0, 40+60, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-40-60);
    [self.view addSubview:self.quarView];
    [self.view bringSubviewToFront:self.quarView];
}

-(void)QuarVIewRemove{
    
    [self.quarView removeFromSuperview];
    _tableview.frame = CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-60);
}
/**
 *   QuarterView代理方法
 */
-(void)Allclick{
    
    _refreshNumb=3;
    [_tableview.header beginRefreshing];
}

-(void)QuarClick:(NSString *)url{
    
    self.QuaRefrshUrl = url;
    _refreshNumb = 4;
    [_tableview.header beginRefreshing];
}
-(void)RefreshQuarWhithWul:(NSString *)url{
    
    [[Manager sharedManager]RequestWhithURL:url AndParameter:nil AndCompletionType:^(id responseObject, DIEError *error) {
        
        ShoolDataModel *allModel = [[ShoolDataModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
        if (_recomAry.count<=0) {
            [_recomAry addObjectsFromArray:allModel.recommend];
        }
        [_listAry addObjectsFromArray:allModel.article_list];
        _infoModel = allModel.page_info;
        
        if (_recomAry.count!=0) {
            [self HeadOfTableview];
        }else{
            _tableview.tableHeaderView = nil;
        }
        
        [_tableview.header endRefreshing];
        [_tableview.footer endRefreshing];
        [_tableview reloadData];

    }];
}

-(NSString *)bqStr{
    
    if (!_bqStr) {
        _bqStr = [NSString string];
    }
    return _bqStr;
}

-(void)HeadClick:(UIButton *)button{
    self.bqStr =  @"切换栏目";
    self.slideBntview.selecLab.text = @"";
    
    _refreshNumb=1;
    [_tableview.header beginRefreshing];
    [self.slideBntview AnimationWhithClick];
    [_ClassifyTableview reloadData];
}

#pragma mark--下拉按键
-(void)TableviewHead{
    /*
     tableview的头 设置高度为40，底层为Bnt
     */
    self.slideBntview = [[SlideBntView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,40)];
    self.slideBntview.deleget = self;
    
    [self.slideBntview.synBnt addTarget:self action:@selector(HeadClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.slideBntview];
}

#pragma mark--slideBntview代理方法
//收回
-(void)TapTopPut{
    _ClassifyTableview.frame = CGRectMake(0, 40, SCREEN_WIDTH,0);
}

//展开
-(void)TapDown{
    _ClassifyTableview.frame = CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-55);
;
    [self.view bringSubviewToFront:_ClassifyTableview];
}

#pragma mark---所有分类标签数据请求
/*数据返回类型为一个大数组*/
-(void)AFNetOfCharacter{
    
    [[Manager sharedManager]AchiveCharactWhithTypeid:self.TypeIndex AndTablePath:[NSString stringWithFormat:@"%@Charact.db", self.DBstr] TableName:[NSString stringWithFormat:@"%@Charact", self.DBstr] AndResult:^(id Charact) {
        
        [_CharaDataAry addObjectsFromArray:Charact];

        [_ClassifyTableview reloadData];
    } Error:^(DIEError *error) {
        [self CharatDataFromSQL];
    }];
}

#pragma mark----第一层列表数据请求
-(void)GetAFNtWhithPage:(NSInteger )page{
    [self QuarVIewRemove];
    
    [[Manager sharedManager]AchiveDataOfSchoolTypeid:self.TypeIndex Page:page SQLTablePath:[NSString stringWithFormat:@"%@.db",self.DBstr] tableName:self.DBstr AndDataAry:_dataAry AndResult:^(id list, id recomment, id pageInfo ,id fourth_classify) {
        
        [_listAry addObjectsFromArray:list];
        _infoModel = pageInfo;
        if (_recomAry.count<=0) {
            _recomAry=[NSMutableArray arrayWithArray:recomment];
            
        }
        
        if (_recomAry.count!=0) {
            [self HeadOfTableview];
        }else{
            _tableview.tableHeaderView = nil;
        }
        
        [_tableview.header endRefreshing];
        [_tableview.footer endRefreshing];
        _tableview.isShowImage = YES;
        [_tableview reloadData];
        
    } AError:^(DIEError *error) {
        [Manager GetHudWhithText:@"网络加载失败" AndFatherView:self.view];
        [self DataFromSQL];
        [_tableview.header endRefreshing];
        [_tableview.footer endRefreshing];
        _tableview.isShowFile = YES;
        [_tableview reloadData];

    }];
}

#pragma mark--触发标签加载列表数据请求
-(void)GetDataOfCharactSnderWhiUrl:(NSString *)url {
        
    [[Manager sharedManager]AchiveBigAndSmallCharectWhithUrl:url AndResult:^(id list, id recomment, id pageInfo,id fourth_classify) {
        
        NSArray *ary = fourth_classify;

        if (ary.count!=0) {
            
            QuartModel *FYmodel = [NSMutableArray arrayWithArray:fourth_classify][0];
            
            if (![FYmodel.title isEqualToString:@""]) {
                [self creatquarView];
                self.quarView.dataArry = [NSMutableArray arrayWithArray:fourth_classify];

            }else{
                [self QuarVIewRemove];
            }
   
        }else{
            [self QuarVIewRemove];
        }

        if (_recomAry.count<=0) {
            [_recomAry addObjectsFromArray:recomment];
        }
        
        [_listAry addObjectsFromArray:list];
        
        _infoModel = pageInfo;
        
        if (_recomAry.count!=0) {
            [self HeadOfTableview];
        }else{
            _tableview.tableHeaderView = nil;
        }
        [_tableview.header endRefreshing];
        [_tableview.footer endRefreshing];
        [_tableview reloadData];
    } AError:^(DIEError *error) {
        [_tableview.header endRefreshing];
        [_tableview.footer endRefreshing];
        [Manager GetHudWhithText:@"请检查网络" AndFatherView:self.view];
    }];
}
//数据库获取列表数据  只存第一层
-(void)DataFromSQL{
    
    [_dataAry removeAllObjects];
    [_recomAry removeAllObjects];
    [_listAry removeAllObjects];
    
    [CGFdbmBase OpenSQlWhiPathName:[NSString stringWithFormat:@"%@.db",self.DBstr]];
    
    [_dataAry addObjectsFromArray:[CGFdbmBase ListWhith:self.DBstr dicName:@"data"]];
    
    _model = [[ShoolDataModel alloc]initWithDictionary:_dataAry.firstObject error:nil];
    [_listAry addObjectsFromArray:_model.article_list];
    if (_recomAry.count<=0) {
        [_recomAry addObjectsFromArray:_model.recommend];
    }
    [_tableview reloadData];
    [self HeadOfTableview];
}
//数据库获取分类标签数据
-(void)CharatDataFromSQL{
    
    [CGFdbmBase OpenSQlWhiPathName:[NSString stringWithFormat:@"%@Charact.db", self.DBstr]];
    
    [_CharaDataAry addObjectsFromArray:[[CGFdbmBase ListWhith:[NSString stringWithFormat:@"%@Charact", self.DBstr] dicName:@"data"] firstObject]];
    [_ClassifyTableview reloadData];
}

#pragma mark--下拉刷新
- (void)loadNewData {
    [_tableview.footer endRefreshing];
    [_dataAry removeAllObjects];
    [_recomAry removeAllObjects];
    [_listAry removeAllObjects];

    if (_refreshNumb==1) {
        [self GetAFNtWhithPage:1];
    }else if (_refreshNumb==2){
        [self GetDataOfCharactSnderWhiUrl:[PramasMontage BigCharact:_bigCharectAid Page:1]];
    }else if(_refreshNumb==3){
        [self GetDataOfCharactSnderWhiUrl:[PramasMontage SmallCharect:_smallCharactAid Page:1]];
        
    }else{
        [self RefreshQuarWhithWul:self.QuaRefrshUrl];
        
    }
}
#pragma mark--上拉加载
- (void)loadMoreData {
    [_tableview.header endRefreshing];
    if (![_infoModel.nextPage isEqualToString:_infoModel.pageCount]) {
        
        if (_refreshNumb==1) {
            [self GetAFNtWhithPage:_infoModel.nextPage.integerValue];
        }else if (_refreshNumb==2){
            [self GetDataOfCharactSnderWhiUrl:[PramasMontage BigCharact:_bigCharectAid Page:_infoModel.nextPage.integerValue]];
        }else if(_refreshNumb==3){
            [self GetDataOfCharactSnderWhiUrl:[PramasMontage SmallCharect:_smallCharactAid Page:_infoModel.nextPage.integerValue]];
            
        }else if (_refreshNumb==4){
            
            NSString *url = [NSString stringWithFormat:@"%@&page=%ld",self.QuaRefrshUrl,(long)_infoModel.nextPage.integerValue];
            [self RefreshQuarWhithWul:url];
        }
    }else{
        [_tableview.footer noticeNoMoreData];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _dataAry = [NSMutableArray array];
    _CharaDataAry = [NSMutableArray array];
    _listAry = [NSMutableArray array];
    _recomAry =[NSMutableArray array];

    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self AFNetOfCharacter];
        [self GetAFNtWhithPage:1];
    });
  
    [self CrectTableview];
    _refreshNumb = 1;
    
}
-(void)CrectTableview{
    _tableview = [[RootTableview alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-40) style:UITableViewStylePlain];
    [self.view addSubview:_tableview];
    _tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableview.tag = 1;
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _tableview.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    _tableview.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [_tableview registerClass:[NewsCell class] forCellReuseIdentifier:@"cell"];
    [self TableviewHead];
    
    __weak typeof(self) weakSelf = self;
    _tableview.TapBlok = ^{
        [weakSelf loadNewData];
    };
    
    _ClassifyTableview =[[UITableView alloc]initWithFrame:CGRectMake(0, 40, SCREEN_WIDTH,0) style:UITableViewStylePlain];
    _ClassifyTableview.separatorStyle = 0;
    _ClassifyTableview.tag = 2;
    _ClassifyTableview.dataSource = self;
    _ClassifyTableview.delegate = self;
    _ClassifyTableview.bounces = NO;
    [_ClassifyTableview registerClass:[CharacterCell class] forCellReuseIdentifier:@"Characell"];
    [self.view addSubview:_ClassifyTableview];
    _ClassifyTableview.tableFooterView = [UIView new];
}
#pragma mark---tableview 头部
-(void)HeadOfTableview{
    
    _recommentView = [[Recomment alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*0.23)];
    
    _recommentView.titleAry = [_recomAry copy];
    __weak typeof(self) weakself = self;
    _recommentView.Click = ^(NSNumber *skin,NSString *AticID){
        
        
        if ([skin isEqual:@1]){
            VideoDescrib *video = [VideoDescrib new];
            video.AticleID = AticID;
            
            [weakself.navigationController  pushViewController:video animated:YES];
        }else{
            NewestAticleCtr *aticle = [NewestAticleCtr new];
            aticle.AticleID =AticID;
            [weakself.navigationController pushViewController:aticle animated:YES];
        }

    };
    _tableview.tableHeaderView = _recommentView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView.tag== 1) {
        return 0;
    }else{
        return 35;
    }
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView.tag==1) {
        return 1;
    }else{
        return _CharaDataAry.count;
       

    }
}

#pragma mark--分类标签
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView.tag==1) {
        return nil;
    }else{
        /*头部高度为35*/
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
        view.backgroundColor = [UIColor whiteColor];
        
        UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 15.5, 4, 15)];
        imgview.image = [UIImage imageNamed:@"title"];
        [view addSubview:imgview];
        
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 100, H(view)-10)];
        _classfyModel = [[ClassiFYModel alloc]initWithDictionary:_CharaDataAry[section] error:nil];
        lable.text = _classfyModel.title;
        [view addSubview:lable];
        
        return view;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag==1) {
        return _listAry.count;
    }else{
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag==1) {
        return _cellHeight+1;
    }else{
        return _CharacCellHeight+1;
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView.tag==1) {
        
        NewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

        if (_listAry.count>0) {
            cell.model =_listAry[indexPath.row];
            _cellHeight = cell.cellHight;

        }
        return cell;

    }else{
        
        CharacterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Characell"];

        ClassiFYModel *model =[[ClassiFYModel alloc]initWithDictionary:_CharaDataAry[indexPath.section] error:nil] ;
        cell.title = self.bqStr;
        cell.classAry = [model.classify_list copy];
        
        _CharacCellHeight = cell.cellHight;
        
#pragma mark---标签bnt，用Block实现
        __weak typeof(self) weakSelf = self;
        cell.ButtionBlock = ^(UIButton *sender){
            if ((sender.tag-10) == model.classify_list.count) {
                [weakSelf SectionSynClick:indexPath.section];
            }else{
                
                ClassListModel *list = model.classify_list[sender.tag-10];
                [weakSelf.slideBntview AnimationWhithClick];
                weakSelf.bqStr = sender.currentTitle;
                
                weakSelf.slideBntview.selecLab.text = sender.currentTitle;
                _refreshNumb=3;
                _smallCharactAid = list.aid.integerValue;
                
                ClassiFYModel *model = [[ClassiFYModel alloc]initWithDictionary:_CharaDataAry[indexPath.section] error:nil];
                
                weakSelf.slideBntview.titleLabel.text = model.title;
            }
            
            [_tableview.header beginRefreshing];
            [_ClassifyTableview reloadData];
            
        };
        
        return cell;
    }
}

#pragma mark---大标签发送数据
-(void)SectionSynClick:(NSInteger )tag{
    
    ClassiFYModel *model = [[ClassiFYModel alloc]initWithDictionary:_CharaDataAry[tag] error:nil];
    self.bqStr = model.title;
    
    [self.slideBntview AnimationWhithClick];
    self.slideBntview.selecLab.text = model.title;
    self.slideBntview.titleLabel.text = @"首页";
    _refreshNumb=2;
    _bigCharectAid = model.typeid.integerValue;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (_listAry.count!=0) {
        NEWAticListModel  *Model3 = _listAry[indexPath.row];
        if (Model3.skin.integerValue == 1){
            VideoDescrib *video = [VideoDescrib new];
            video.AticleID = Model3.AtcID;

            [self.navigationController  pushViewController:video animated:YES];
        }else{
            NewsCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            NewestAticleCtr *aticle = [NewestAticleCtr new];
            aticle.AticleID = cell.AticleID;
            [self.navigationController pushViewController:aticle animated:YES];
        }
        
    }
}

//-(void)didReceiveMemoryWarning{
//    
//    [super didReceiveMemoryWarning];//即使没有显示在window上，也不会自动的将self.view释放。
//    
//    if ([self.view window] == nil) {
//        
//        self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
//        
//    }
//}

@end